/*
 * 作者: junmu
 * 时间: 2025-07-22
 */
package com.hzbc.faceattendance.service.impl;

import com.hzbc.faceattendance.model.AttendanceRecord;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.ByteArrayOutputStream;
import com.hzbc.faceattendance.model.AdminUser;
import com.hzbc.faceattendance.repository.AttendanceRecordRepository;
import com.hzbc.faceattendance.repository.UserRepository;
import com.hzbc.faceattendance.service.IAttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class AttendanceServiceImpl implements IAttendanceService {
    @Override
    public List<AttendanceRecord> getAttendanceRecordsByDate(Date date) {
        return attendanceRecordRepository.findByEntryTimeBetween(date, new Date(date.getTime() + 86400000), Pageable.unpaged()).getContent();
    }

    @Autowired
    private AttendanceRecordRepository attendanceRecordRepository;
    
    @Autowired
    private UserRepository userRepository;

    @Override
    public Page<AttendanceRecord> getAllRecords(Date startDate, Date endDate, String keyword, Pageable pageable) {
        if (startDate == null || endDate == null) {
            // 默认查询当天记录
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            startDate = calendar.getTime();

            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            endDate = calendar.getTime();
        }
        if (keyword != null && !keyword.isEmpty()) {
            return attendanceRecordRepository.findByWhiteListNameContainingAndEntryTimeBetween(keyword, startDate, endDate, pageable);
        }
        
        return attendanceRecordRepository.findByEntryTimeBetween(startDate, endDate, pageable);
    }

    @Override
    public Page<AttendanceRecord> getEnteredRecords(Date startDate, Date endDate,String keyword, Pageable pageable) {
        if (startDate == null || endDate == null) {
            // 默认查询当天记录
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            startDate = calendar.getTime();

            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            endDate = calendar.getTime();
        }
        return attendanceRecordRepository.findByWhiteListNameContainingAndStatusAndEntryTimeBetween(keyword, 0, startDate, endDate, pageable);
    }

    @Override
    public Page<AttendanceRecord> getLeftRecords(String keyword,Date startDate, Date endDate, Pageable pageable) {
        if (startDate == null || endDate == null) {
            Date today = new Date();
            startDate = today;
            endDate = today;
        }
        return attendanceRecordRepository.findByWhiteListNameContainingAndStatusAndEntryTimeBetween(keyword,1, startDate, endDate, pageable);
    }
    
    @Override
    public List<AdminUser> getAbsentRecords(Date date, Long classId) {
        // 1. 获取当天所有考勤记录中的用户ID
        List<Long> attendedUserIds = attendanceRecordRepository
            .findByEntryTimeBetween(date, date, Pageable.unpaged())
            .stream()
            .map(record -> record.getWhitelist().getId())
            .distinct()
            .toList();
            
        // 2. 查询所有用户
        List<AdminUser> allAdminUsers = classId != null ?
            userRepository.findByClassId(classId) : 
            userRepository.findAll();
            
        // 3. 筛选出未出现在考勤记录中的用户
        return allAdminUsers.stream()
            .filter(user -> !attendedUserIds.contains(user.getId()))
            .toList();
    }
    
    @Override
    public byte[] exportAttendanceReport(Date date) throws Exception {
        // 1. 获取当天的考勤记录
        List<AttendanceRecord> records = getAttendanceRecordsByDate(date);

        // 2. 创建Excel工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("考勤记录");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("姓名");
            headerRow.createCell(1).setCellValue("工号/学号");
            headerRow.createCell(2).setCellValue("状态");
            headerRow.createCell(3).setCellValue("时间");

            // 填充数据
            int rowNum = 1;
            for (AttendanceRecord record : records) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(record.getWhitelist().getName());
                row.createCell(1).setCellValue(record.getWhitelist().getId());
                String statusStr = record.getStatus()==0?"进入":"离开";
                row.createCell(2).setCellValue(statusStr);
                row.createCell(3).setCellValue(record.getEntryTime().toString());
            }

            // 自动调整列宽
            for (int i = 0; i < 4; i++) {
                sheet.autoSizeColumn(i);
            }

            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }

    @Override
    public AttendanceRecord save(AttendanceRecord attendanceRecord) {
        return attendanceRecordRepository.save(attendanceRecord);
    }

    @Override
    public AttendanceRecord findRecordByNameAndStatus(String whiteName, Integer status) {
        return attendanceRecordRepository.findByWhiteListNameAndStatus(whiteName, status);
    }
}